<template>
  <div>
    <el-button @click="startMouseAddData(MapType.Polygon)" :disabled="mouseToolData.open">添加面</el-button>
    <el-button @click="startMouseAddData(MapType.Polyline)" :disabled="mouseToolData.open">添加线</el-button>
    <el-button @click="startMouseAddData(MapType.Marker)" :disabled="mouseToolData.open">添加点</el-button>


    <!-- 隐藏原生文件输入 -->
    <input type="file" accept=".json" @change="addJsonFile">
    <el-button type="primary" :icon="Edit" :disabled="mouseToolData.type !== ''" @click="openEditDialog">添加</el-button>

    <AMapView @updateMap="updateMap" @updateCoordsy="updateCoordsy" :can-change-layer="canChangeLayer" />

    <div class="input-card" style="width: 10rem" v-if="mouseToolData.open">
      <div style="color: red">请在点图中绘制</div>
      <el-input v-model="mouseToolData.name" placeholder="要素名称" />
      <el-button @click="stopMouseAddData(true)">保存</el-button>
      <el-button @click="stopMouseAddData(false)">取消</el-button>
    </div>
    <div>
      <el-tag v-for="tag in elementInTop" :key="tag.featureData.name" closable @close="handleClose(tag)"
        @click="moveTo(tag)">
        {{ tag.featureData.name }}
      </el-tag>
      <el-table :data="[...elementInPage]" style="width: 100%; margin-top: 10px">
        <el-table-column type="index" label="序号" />
        <el-table-column label="数据">
          <template #default="{ row }">
            {{ row.featureData.name || row }}<span v-if="row.featureData.top">&#9875;</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="danger" :icon="Delete" @click="deleteMapData(row)" circle />
            <el-button :icon="Location" @click="moveTo(row)" circle />
            <el-button :icon="Download" @click="exportJSON(row)" circle />
          </template>
        </el-table-column>
        <el-table-column label="设置">
          <template #default="{ row }">
            <el-button :icon="Setting" @click="openEditDialog(row)" circle />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize" :pager-count="11"
        layout="prev, pager, next, ->, total" :total="pageData.count" @current-change="handleCurrentPageChange"
        @size-change="handlePageSizeChange" />
    </div>

    <EditDialog v-if="editElementStore.visible" @save="saveEditDialog" />
  </div>
</template>

<script setup lang="ts" name="MyMap">
import { ref, reactive, computed, watch, onMounted, VNodeRef, toRefs } from 'vue'
import {
  Delete,
  Edit,
  Location,
  Download,
  Setting
} from '@element-plus/icons-vue'


import { DialogType, MapType } from '@/class/map/myMapOpt'

import { reqGetMapdataByPage, reqGetMapdataCount, reqGetMapDataTop } from '@/api/mapdata'
import AMapView from '@/views/map/container/AMapView.vue'

import { warningMessage } from '@/utils/message'

import { MapCoordSys } from '@/class/map/myMapOpt'
import { useMapInDatabase } from '../../stores/map/mapInDatabase'

import { getMapDateByType } from '@/utils/map'
import { FeatureDataInterface, MapData } from '@/class/map/MapData'
import { storeToRefs } from 'pinia'
import { useEditElementStore } from '@/stores/map/mapInEditor'
import EditDialog from "@/views/map/dialog/EditDialog.vue"
import { Polygon, PolygonData } from '@/class/map/Polygon'
import { getRandomColor } from '@/utils/utils'
import { Polyline, PolylineData } from '@/class/map/Polyline'
import { Marker, MarkerData } from '@/class/map/Marker'
import { useRoute } from 'vue-router'
import { number } from 'echarts'
const mapInDatabase = useMapInDatabase()
let { elementInPage, elementInTop } = storeToRefs(mapInDatabase)
// let route = useRoute()

// let currentPage = (query.value.currentPage as number)|5

// 响应式状态
const mouseToolData = reactive({
  open: false,
  overlays: [],
  mouseTool: null,
  name: '',
  type: ''
})

const pageData = reactive({
  count: 0,
  pageSize: 5,
  currentPage: 1
})


const mapCoordSys = ref(MapCoordSys.CJ02)
const canChangeLayer = ref(true)
let map: any = reactive(null)
const feature = reactive({
  page: [],
  top: []
})
// 方法
const updateMap = (newMap) => {
  map = newMap
  console.log(map.dragEnable);

  getAllDataInStore()
}

const updateCoordsy = (newCoord) => {
  mapCoordSys.value = newCoord
}

// 初始化数据
onMounted(async () => {

})

// 数据获取逻辑
const getAllDataInStore = async () => {
  await getElementInPage()
  await getElementInTop()
}

const getElementInPage = async () => {
  const result = await reqGetMapdataCount()
  pageData.count = result.data
  if (pageData.count <= 0) {
    warningMessage("暂无数据")
    return
  }
  mapInDatabase.getElementInPage(pageData.currentPage,pageData.pageSize);
}
const getElementInTop = async () => {
  mapInDatabase.getElementInTop()
}
// 其他方法保持类似结构，使用箭头函数和响应式引用...
// 这里需要继续补充剩余的方法实现，保持与原有功能一致

// 注意：需要将原methods中的方法转换为组合式API的函数形式
// 例如原methods中的startMouseAddData：
const startMouseAddData = (type) => {
  canChangeLayer.value = false
  mouseToolData.open = true
  //@ts-ignore 
  mouseToolData.mouseTool = new AMap.MouseTool(map)
  mouseToolData.type = type

  mouseToolData.mouseTool.on('draw', (e) => {
    mouseToolData.overlays.push(e.obj)
  })

  switch (type) {
    case MapType.Marker: {
      mouseToolData.mouseTool.marker({
        //同Marker的Option设置
      });
      break;
    }
    case MapType.Polyline: {
      mouseToolData.mouseTool.polyline({
        strokeColor: '#80d8ff'
        //同Polyline的Option设置
      });
      break;
    }
    case MapType.Polygon: {
      mouseToolData.mouseTool.polygon({
        fillColor: '#00b0ff',
        strokeColor: '#80d8ff'
        //同Polygon的Option设置
      });
      break;
    }
  }
  //移除事件
  map.getAllOverlays().forEach(removeClickEvents)
}
/**
 * 导入json 通过json文件添加数据
 * @param event
 */
const addJsonFile = (event) => {
  event.target.files[0].text().then(target => {
    const data = JSON.parse(target);
    var myMap = getMapDateByType(data)
    myMap.upload();
    getAllDataInStore();
  })
  stopMouseAddData(false);
}
// 创建一个 ref 对象
const fileInput = ref<HTMLInputElement | null>(null);
const triggerFileInput = () => {
  // 通过ref触发隐藏的input点击
  // $refs.fileInput.click();
  fileInput.value.click();
}
/**
     * 关闭鼠标添加数据
     * @param isSave
     */
const stopMouseAddData = (isSave: boolean) => {
  if (isSave) {
    let opt;
    let mapData;
    switch (mouseToolData.type) {
      case MapType.Polygon:
        var path = [];
        for (let i = 0; i < mouseToolData.overlays.length; i++) {
          path.push(mouseToolData.overlays[i].getOptions().path)
        }
        const polygon = new Polygon({
          path,
          fillColor: getRandomColor(),
          strokeColor: getRandomColor(),
          fillOpacity: 0.5
        })
        mapData = new MapData({
          type: MapType.Polygon,
          top: false,
          name: mouseToolData.name || MapType.Polygon + Date.now(),
          coordsys: mapCoordSys.value
        })
        opt = new PolygonData({ featureData: mapData, featureMap: polygon });
        break;
      case MapType.Polyline:
        var path = [];
        for (let i = 0; i < mouseToolData.overlays.length; i++) {
          path.push(mouseToolData.overlays[i].getOptions().path)
        }
        const polyline = new Polyline({
          path,
          strokeColor: getRandomColor()
        })
        mapData = new MapData({
          type: MapType.Polyline,
          top: false,
          name: mouseToolData.name || MapType.Polyline + Date.now(),
          coordsys: mapCoordSys.value
        })
        opt = new PolylineData({ featureData: mapData, featureMap: polyline })
        break;
      case MapType.Marker:
        const position = mouseToolData.overlays[0].getPosition().toJSON()
        mapData = new MapData({
          type: MapType.Marker,
          top: false,
          name: mouseToolData.name || MapType.Marker + Date.now(),
          coordsys: mapCoordSys.value
        })
        const marker = new Marker({
          position
        })
        opt = new MarkerData({ featureData: mapData, featureMap: marker })
        break;
    }
    opt.upload().then(result => {
      if (result) {
        getElementInPage()
      }
    })
  } else {
    //取消修改后同样更新数据-->添加要素点击事件
    getElementInPage()
  }
  mouseToolData.type = ""
  mouseToolData.overlays = []
  mouseToolData.open = false
  mouseToolData.name = ""
  mouseToolData.mouseTool.close(true)
  canChangeLayer.value = true
}
const handleClose = (tag: FeatureDataInterface) => {
  tag.featureData.top = false
  tag.update().then(result => {
    if (result) {
      getElementInTop()
    }
  })
}
const exportJSON = (row: FeatureDataInterface) => {
  row.getJSON();
}
const moveTo = (row: FeatureDataInterface) => {
  row.moveTo(map)
}

const deleteMapData = (row: FeatureDataInterface) => {
  row.deleteElement().then(result => {
    getElementInPage();
  })
}

const handleCurrentPageChange = (page) => {
  pageData.currentPage = page
  getElementInPage()
}
const handlePageSizeChange = (size) => {
  pageData.pageSize = size;
  getElementInPage()
}
// 其他方法类似转换
watch(elementInPage.value, () => {
  const mapElements = elementInPage.value
  // if (mapElements.length !== feature.page.length) {
  if (true) {
    feature.page = feature.page.filter((item, index) => {
      const flag = mapElements.find(element => {
        return item.getExtData().id === element.featureData.id;
      })
      if (flag === undefined) {
        // console.log("count before remove is ",map.getAllOverlays().length); 
        item.setMap()
        console.log("removePageValue:",item.getOptions().extData);        
        // console.log("count after remove is ",map.getAllOverlays().length);  
        return false;
      }else{
        return true
      }
    })
    mapElements.forEach((element) => {
      let gaodeMapFeature = null;
      try {
        gaodeMapFeature = element.addToMap(map, mapCoordSys.value)
      } catch (e) {
        console.error(e)
        warningMessage("要素有误：" + element.featureData.name)
      }
      feature.page.push(gaodeMapFeature);
      gaodeMapFeature.clearEvents("click");
      addClickEvents(gaodeMapFeature, element);
    })
  }
})
watch(elementInTop.value, () => {
  const mapElements = elementInTop.value
  // if (feature.top.length !== elementInTop.value.length) {
  if (true) {
    feature.top = feature.top.filter((item, index) => {
      const flag = mapElements.find(element => {
        return item.getExtData().id === element.featureData.id;
      })
      if (flag === undefined) {
        console.log("removeTopValue:",item.getOptions().extData);
        return false;
      }else{
        return true;
      }
    })
    mapElements.forEach((element) => {
      let gaodeMapFeature = null;
      try {
        gaodeMapFeature = element.addToMap(map, mapCoordSys.value)
      } catch (e) {
        console.error(e)
        warningMessage("要素有误：" + element.featureData.name)
      }
      feature.top.push(gaodeMapFeature);
      gaodeMapFeature.clearEvents("click");
      addClickEvents(gaodeMapFeature, element);
    })
  }
})
/**
 * 添加点击事件
 * @param feature GaodeMap中需要添加的事件的feature
 * @param item feature对应的MyMap对象
 */
const addClickEvents = (feature, item) => {
  feature.on('click', () => {
    openEditDialog(item)
  })
}
const removeClickEvents = (feature) => {
  feature.clearEvents("click");
}
const editElementStore = useEditElementStore()
/**
 * 打开修改窗口
 * @param row 编辑的要素
 */
const openEditDialog = (row: FeatureDataInterface | undefined) => {
  if (row && row.getCopy) {
    let editData = row.getCopy()
    editElementStore.setElement(editData)
    editElementStore.openEdit(DialogType.EditData)
  }
  else {
    editElementStore.addType = MapType.Marker
    editElementStore.openEdit(DialogType.AddData)
  }
}
const saveEditDialog = () => {
  const editElement = editElementStore.element
  // let updatePage = false, updateTop = false;
  elementInPage.value.forEach(itemInPage => {
    if (itemInPage.featureData.id === editElement.featureData.id) {
      if (JSON.stringify(itemInPage) !== JSON.stringify(editElement)) {
        Object.assign(itemInPage, editElement)
        updateInMap(editElement.featureData.id, editElement)
        if (editElement.featureData.top === true) {
          elementInTop.value.push(editElement)
        }
      }
    }
  })
  elementInTop.value.forEach(itemInTop => {
    if (itemInTop.featureData.id === editElement.featureData.id) {
      if (JSON.stringify(itemInTop) !== JSON.stringify(editElement)) {
        Object.assign(itemInTop, editElement)
        updateInMap(editElement.featureData.id, editElement)
        if (editElement.featureData.top === false) {
          debugger
          elementInTop.value = elementInTop.value.filter(item => { return item.featureData.id !== editElement.featureData.id })
        }
      }
    }
  })
  editElementStore.visible = false
}
const updateInMap = (id: string, editElement: FeatureDataInterface) => {
  feature.page.forEach(pageItem => {
    pageItem.setMap()
  })
}
</script>

<style scoped>
/* 样式部分保持原样 */
.input-card {
  /* ... */
}

/* 其他样式规则... */
</style>